package com.shuqing.download.engine.distribute.dispatch.monitor;

import com.shuqing.download.engine.DefaultHandler;
import com.shuqing.download.engine.DownLoadTaskDto;
import com.shuqing.download.engine.constants.EventEnum;
import com.shuqing.download.engine.constants.TaskStatusEnum;
import com.shuqing.download.engine.distribute.dispatch.TaskContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听局长
 * @author wangshuqing
 * @date 2023/3/4 17:34
 */
@Component
@Slf4j
public class MonitorLeader implements DefaultHandler {

    @Autowired
    private List<Notify> notifies;
    @Autowired
    private List<Event> events;
    /**
    * 委派消息
    * @date 2023/3/4 17:36
    * @author wangshuqing
    * @param context
    * @param newStatus
    * @param ex
    * */
    public void assignNotify(TaskContext context, TaskStatusEnum newStatus,Exception ex){
        //重置消耗时间
        context.resetConsumeTime();
        context.updateStatus(newStatus,(n,o)->{
            String errorMsg=ex ==null ? "" : ex.getMessage();
            DownLoadTaskDto task=context.getTask();
            //触发事件
            //pushEvent(context,EventEnum.STATUS_CHANGE,ex == null,errorMsg,o.getDesc(),n.getDesc());
            //通知
            pullNotify(task,context,newStatus,errorMsg);
        });
    }

    /**
    * 委派消息
    * @date 2023/3/4 18:35
    * @author wangshuqing
    * @param context
    * @param newStatus
    * */
    public void assignSuccessNotify(TaskContext context, TaskStatusEnum newStatus){
        assignNotify(context,newStatus,null);
    }




    private void pullNotify(DownLoadTaskDto task,TaskContext context,TaskStatusEnum newStatus,String errorMsg){
        log.info("下载任务{}触发状态消息通知:{}",context.getTask().getId(),newStatus.getDesc());
        for(Notify notify:notifies){
            try{
                notify.discover(context,newStatus,errorMsg);
            }catch (Exception exception){
                log.error("下载任务{},消息通知处理失败:{}",task.getId(),exception);
            }
        }
    }
    public void assignSuccessEvent(TaskContext context, EventEnum eventEnum,Object... args){
        pushEvent(context,eventEnum,true,null,args);
    }

    private void pushEvent(TaskContext context, EventEnum eventEnum, Boolean success, String errorMsg,Object... args){
        //重置消耗时间
        log.info("下载任务{}触发事件通知:{}",context.getTask().getId(),eventEnum.getDesc());
        context.resetConsumeTime();
        DownLoadTaskDto task=context.getTask();
        for(Event event:events){
            try{
                event.discover(context,eventEnum,success,errorMsg,args);
            }catch (Exception exception){
                log.error("下载任务{},事件通知处理失败:{}",task.getId(),exception);
            }
        }
    }
}
